package com.naiterui.ehp.bs.consult.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.naiterui.ehp.bp.bo.consult.SuperviseVideoBO;
import com.naiterui.ehp.bp.bo.consult.SuperviseVideoInfoBO;
import com.naiterui.ehp.bp.domain.DrVideoConsult;
import com.naiterui.ehp.bp.domain.DrVideoConsultUrl;
import com.naiterui.ehp.bp.domain.VideoConsultMessage;
import com.naiterui.ehp.bs.consult.repository.DrVideoConsultRepository;
import com.naiterui.ehp.bs.consult.repository.DrVideoConsultUrlRepository;
import com.naiterui.ehp.bs.consult.repository.VideoConsultMessageRepository;
import com.naiterui.ehp.bs.consult.service.IVideoSuperviseService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author luao
 * @date 2022/5/19 5:18 PM
 **/
@Service
@RequiredArgsConstructor
public class VideoSuperviseServiceImpl implements IVideoSuperviseService {

    @Value("${ehp.domain.img}")
    private String imgHost;

    private final DrVideoConsultRepository videoConsultRepository;
    private final VideoConsultMessageRepository videoConsultMessageRepository;
    private final DrVideoConsultUrlRepository videoConsultUrlRepository;

    @Override
    public SuperviseVideoBO getVideoSuperviseInfo(String start, String end) {
        SuperviseVideoBO result = new SuperviseVideoBO();
        List<SuperviseVideoInfoBO> videos = new ArrayList<>();
        Date startD = DateUtil.parse(start, DatePattern.NORM_DATETIME_PATTERN);
        Date endD = DateUtil.parse(end, DatePattern.NORM_DATETIME_PATTERN);
        List<Integer> status =
            Arrays.asList(DrVideoConsult.VIDEO_CONSULT_STATUS_CANCEL, DrVideoConsult.VIDEO_CONSULT_STATUS_COMPLETE);
        List<DrVideoConsult> videoConsults =
            videoConsultRepository.findByConsultTimeBetweenAndVideoConsultStatusIn(startD, endD, status);

        if (!CollectionUtils.isEmpty(videoConsults)) {
            Set<Long> videoConsultIds = videoConsults.stream().map(e -> e.getId()).collect(Collectors.toSet());
            List<VideoConsultMessage> videoConsultMessages =
                videoConsultMessageRepository.findByVideoConsultIdIn(videoConsultIds);
            Map<Long, List<VideoConsultMessage>> messageMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(videoConsultMessages)) {
                messageMap = videoConsultMessages.stream()
                    .collect(Collectors.groupingBy(VideoConsultMessage::getVideoConsultId));
            }

            List<DrVideoConsultUrl> videoConsultUrls =
                videoConsultUrlRepository.findByVideoConsultIdIn(videoConsultIds);
            Map<Long, DrVideoConsultUrl> videoConsultUrlMap = videoConsultUrls.stream()
                .collect(Collectors.toMap(DrVideoConsultUrl::getVideoConsultId, v -> v, (a, b) -> b));

            for (DrVideoConsult videoConsult : videoConsults) {
                List<VideoConsultMessage> messages = messageMap.get(videoConsult.getId());
                List<Long> recomIds = new ArrayList<>();
                Map<Integer, VideoConsultMessage> map = videoConsultMessages.stream()
                    .collect(Collectors.toMap(VideoConsultMessage::getType, v -> v, (v1, v2) -> v1));
                // String diseaseId = getContent(map, VideoConsultMessage.VIDEO_CONSULT_TYPE_TO_DISEASE);
                // String medicalRecordId = getContent(map, VideoConsultMessage.VIDEO_CONSULT_TYPE_TO_CASE);
                if (CollectionUtil.isNotEmpty(messages)) {
                    // 处方ID
                    recomIds = messages.stream()
                        .filter(msg -> msg.getType().equals(VideoConsultMessage.VIDEO_CONSULT_TYPE_TO_RECOM)
                            && videoConsult.getId().equals(msg.getVideoConsultId()))
                        .map(msg -> Long.parseLong(msg.getContent())).collect(Collectors.toList());
                }

                DrVideoConsultUrl videoConsultUrl = videoConsultUrlMap.get(videoConsult);
                videos.add(SuperviseVideoInfoBO.builder().videoConsultId(videoConsult.getId())
                    .orderSn(videoConsult.getOrderSn()).patientId(videoConsult.getPatientId())
                    .doctorId(videoConsult.getDoctorId()).createdAt(videoConsult.getConsultTime()).recomIds(recomIds)
                    .price(videoConsult.getPrice()).consultStatus(videoConsult.getVideoConsultStatus())
                    .refusalReason(videoConsult.getRefusalReason()).changedAt(videoConsult.getChangedAt())
                    .inquirerId(videoConsult.getInquirerId())
                    .videoUrl(Optional.ofNullable(videoConsultUrl).map(v -> imgHost + v.getVideoUrl()).orElse(""))
                    .conditionDesc(videoConsult.getConditionDesc()).diagnosis(videoConsult.getDiagnosis())
                    .offlineDiagnosis(videoConsult.getOfflineDiagnosis()).build());
            }
        }
        result.setVideos(videos);
        return result;
    }
}
